package com.kexun.common.utils;

import com.alibaba.fastjson.JSON;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.print.event.PrintJobAttributeEvent;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;

public class DingUtils {


    private static final String appSecret = "wgPDPfZFU6mbK3dZpZukgVGhiph8rTnpg1Jti4LmHqnQlOR7slJ9J40CXrU7O2zu";

    public static final String appId = "dingoatkrawlcr4kr9eibz";

    public static String getDingInfo(String code) {
        String url = "https://oapi.dingtalk.com/sns/getuserinfo_bycode?accessKey=%s&timestamp=%s&signature=%s";
        Long timestamp = System.currentTimeMillis();
        url = String.format(url, appId, timestamp, getSign(timestamp));
        HashMap<String, String> param = new HashMap<>();
        param.put("tmp_auth_code", code);
        return HttpUtils.sendPost(url, JSON.toJSONString(param));

    }


    public static String getSign(long timestamp) {
        try {
            String stringToSign = timestamp + "";
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(DingUtils.appSecret.getBytes("UTF-8"), "HmacSHA256"));
            byte[] signatureBytes = mac.doFinal(stringToSign.getBytes("UTF-8"));
            String signature = new String(Base64.encodeBase64(signatureBytes));
            String urlEncodeSignature = urlEncode(signature);
            return urlEncodeSignature;
        } catch (Exception e) {
            return "";
        }
    }

    public static String urlEncode(String value) {
        if (value == null) {
            return "";
        }
        try {
            String encoded = URLEncoder.encode(value, "utf-8");
            return encoded.replace("+", "%20").replace("*", "%2A")
                    .replace("~", "%7E").replace("/", "%2F");
        } catch (UnsupportedEncodingException e) {
            throw new IllegalArgumentException("FailedToEncodeUri", e);
        }
    }

}
